$(function(){
	$.ajax({ 				  		
			url:baseUrl+'wechat/login/get_jssdk_config',	
			type:'GET',				
			dataType:"json",	
			data:{url:window.location.href},	
	        success:function(data){
	        	if(data.code!=200){	        		
				 	dialogshow("错误",data.description);	
				 	
				}else{
					var js_dk=data.data;
					wxconfig(js_dk.appid.toString(),Number(js_dk.timestamp),js_dk.noncestr.toString(),js_dk.signature.toString())				
				}
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
					dialogshow("错误",XMLHttpRequest.status);	
					
			}
    	});
    	
    	//批量上传图片
    	$('.uploadcon').on('touchend','#uploaderInput',function(e){
    		if(!$(".uploadoper").find("a").eq(0).is(":hidden")){
    			$(".uploadoper").find("a").eq(0).hide();
    			$(".uploadoper").find("a").eq(1).show();
    		}    		
			if(imageArray.length==0){
				$(".uploadoper").find("a").eq(1).attr("on","true");
				var img_count=$(this).attr("large_image_num");
				if(img_count>0){
					if(img_count>9){
						//$(this).attr("large_image_num",count-9);
						chooseImage(9);
					}else{						
						chooseImage(img_count);
						//$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
					}
				}else{
					$(".dialog_tips").show().find(".dialog_txt").text("最多只能上传"+$(this).attr("image_num")+"张照片");	
					setTimeout(function(){$(".dialog_tips").hide()},1200)
				}
			}else{
				$(".dialog_tips").show().find(".dialog_txt").text("正在上传照片，请稍后...");	
				setTimeout(function(){$(".dialog_tips").hide()},1200)
			}
		})
    	
    	//微信上传失败重新上传
    	/*$(document).on('touchend','.wx_uprefresh',function(e){
    		alert(1);
    		$(".uploadoper").find("a").eq(1).attr("on","true");
    		var item=$(this).closest('li');
    		wxreshresh(item.find('.upload_img').attr('src'),item.attr('name'));
    		
		})*/
		
		$(document).on('click','.uploadbox .weui-uploader__file',function(e){
			if($(this).children().hasClass('wx_uprefresh')){				
	    		$(".uploadoper").find("a").eq(1).attr("on","true");
	    		var item=$(this).closest('li');
	    		wxreshresh(item,item.find('.upload_img').attr('src'),item.attr('name'));
			}
    		
    		
		})
    	
})
//通过config接口注入权限验证配置
function wxconfig(appId,timestamp,nonceStr,signature){
	wx.config({
      debug: false,
      appId: appId,
      timestamp: timestamp,
      nonceStr: nonceStr,
      signature: signature,
      jsApiList: [        
        'checkJsApi',
        'onMenuShareTimeline',
        'onMenuShareAppMessage',
        'onMenuShareQQ',
        'onMenuShareWeibo',
        'onMenuShareQZone',
        'hideMenuItems',
        'showMenuItems',
        'hideOptionMenu',
        'showOptionMenu',
		'chooseImage',
		'previewImage',
		'uploadImage',
		'downloadImage'	
      ]
  });
	
}

wx.ready(function() {
	// 1 判断当前版本是否支持指定 JS 接口，支持批量判断
	wx.checkJsApi({
		jsApiList: [
		 	'chooseImage',
		 	'onMenuShareTimeline',
	        'onMenuShareAppMessage',
	        'onMenuShareQQ',
	        'onMenuShareWeibo',
	        'onMenuShareQZone',
	        'hideMenuItems',
	        'hideOptionMenu',
       		'showOptionMenu',
	        'showMenuItems',
			'getNetworkType',
			'previewImage'
		], // 需要检测的JS接口列表，所有JS接口列表见附录2,
		success: function(res) {
			// 以键值对的形式返回，可用的api值true，不可用为false
			// 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
				wx.hideOptionMenu();//隐藏分享菜单
			
		
	 }
	});
})
var imageArray=new Array;//临时存储选择的图片

function chooseImage(count){	
	wx.chooseImage({
    count: count, // 默认9
    sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
    success: function (res) {
//      var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
		//console.log(res)
		//alert(JSON.stringify(res));		
		imageArray=res.localIds;
		if(res.localIds.length>0){
			/*if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    		getImageData()
	    	}else{
	    	//调用微信的上传接口
 			wx_upload();
	    	}*/
	    	
	    	 if (window.__wxjs_is_wkwebview){
	    	 	getImageData();
	    	 }else{
	    	 	//调用微信的上传接口
 				wx_upload();	
	    	 }
		}else{
			 $(".uploadoper").find("a").eq(1).removeAttr("on");
		}
		
		
    }
	
	});
	
}



function getImageData(){
	$(".uploadoper").find("a").eq(1).attr("on","true");
	 var length = imageArray.length;
	if(length > 0){
		var i = 0; 
		var base64onupload = function() {	
		  wx.getLocalImgData({
		      localId: imageArray[i],
		      success: function (res) {
		      	var localData;
		      	 localData  = res.localData.replace('jgp','jpeg');		      	
				 	var data=new Object;
					  data.name=getCurrenTemptime('');			 
					  data.base64url=localData;
				      data.compress=true;
					 wexingetchange(data,function(){
					 	if(i !=(length-1)){                                  		
	                          i++;
	                          base64onupload();
	                        }else{
	                        imageArray=[];
	                        $(".uploadoper").find("a").eq(1).removeAttr("on");
	                        
	                     	}
					 });
			  }
		  });
		
		}
		base64onupload();
	}
	
}


//调用微信的上传接口
function wx_upload(){
	 var length = imageArray.length;
	if(length > 0){
		
		var i = 0; 
		var onupload = function() {
		var localIds = imageArray[i];
		var name= getCurrenTemptime('');
		var li='<li class="weui-uploader__file weui-uploader__file_status" name="'+name+'">'+
						               	'<div class="upload_img" style="background-image:url('+localIds+')" src="'+localIds+'"></div>'+
						               	'<div class="weui-uploader__file-content la-ball-beat la-sm"><i></i><i></i><i></i> </div>'+
					              	 '</li>';				                
			$("#uploaderFiles").prepend(li);
		wx.uploadImage({
		 	localId: localIds,
		 	isShowProgressTips: 0,
		 	success: function(res) {		 			 
		 			if(i < length) {
		 				/*baseAjax('other/image/upload_image2', 'POST', {
		 					user_id: user_id,
		 					media_id: res.serverId,		 					
		 					work_id: workid
		 				}, function(result) {
							var item=$('#uploaderFiles li[name="'+name+'"]');
							item.addClass("upload_sucess");
							item.find(".la-ball-beat").remove();					
							if(result.data.quality!=0){//照片的一边小于900    照片像素过低可能导致，图片模糊   0=正常；1=比例不符合；2=像素不符合
								item.append('<div class="upload_i_worn"><i class="weui-icon-warn"></i> </div>');
								console.log('quality' +result.data.quality);
							}							
							item.append('<div class="delimportimg"><i class="fa fa-close fa-fw"></i></div>');	
							item.removeClass("weui-uploader__file_status");
							$(".upload_num").text($(".upload_sucess").length);
							$(".uploadoper").find("a").eq(1).show().siblings("a").hide();
							$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
							
		 					if(i !=(length-1)){                                  		
	                          i++;
	                          onupload();
	                        }else{
	                        	
	                        imageArray=[];
	                        $(".uploadoper").find("a").eq(1).removeAttr("on");
	                        
	                     	}
		 				
		 				})*/
		 				var  obj={
		 					user_id: user_id,
		 					media_id: res.serverId,		 					
		 					work_id: workid
		 					}
		 				$.ajax({ 			  		
							url:baseUrl+'other/image/upload_image2',	
							type:'POST',
							dataType:"json",		
							data:obj,		
					        success:function(data){
					        	var result=data;
					        	if(result.code!=200){ 
									 dialogshow("提示",data.description);
									 if(!$("#loadtoast").is(":hidden")){
									 	$("#loadtoast").hide();
									 }
									 var item=$('#uploaderFiles li[name="'+name+'"]')
									item.find(".la-ball-beat").remove();
									item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
									
									 
								}else{
									var item=$('#uploaderFiles li[name="'+name+'"]');
									item.addClass("upload_sucess");
									item.find(".la-ball-beat").remove();					
									if(result.data.quality!=0){//照片的一边小于900    照片像素过低可能导致，图片模糊   0=正常；1=比例不符合；2=像素不符合
										item.append('<div class="upload_i_worn"><i class="weui-icon-warn"></i> </div>');
										console.log('quality' +result.data.quality);
									}							
									item.append('<div class="delimportimg"><i class="fa fa-close fa-fw"></i></div>');	
									item.removeClass("weui-uploader__file_status");
									$(".upload_num").text($(".upload_sucess").length);
									$(".uploadoper").find("a").eq(1).show().siblings("a").hide();
									$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
									
								}
								if(i !=(length-1)){                                  		
			                         i++;
			                         onupload();
			                    }else{
			                        	
			                     imageArray=[];
			                     $(".uploadoper").find("a").eq(1).removeAttr("on");
			                        
			                    }
							},
							error: function(XMLHttpRequest, textStatus, errorThrown){	
									if(XMLHttpRequest.status==0){
										dialogshow("提示",'加载失败，请重新加载！');
										 if(!$("#loadtoast").is(":hidden")){
									 	$("#loadtoast").hide();
										 }
									}else{
										dialogshow("提示",XMLHttpRequest.status);	
									}
									var item=$('#uploaderFiles li[name="'+name+'"]')
									item.find(".la-ball-beat").remove();
									item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
												
							}
					  });
		 				
		 				
		 			}
		 		},fail: function (res) {
                    var item=$('#uploaderFiles li[name="'+name+'"]')
					item.find(".la-ball-beat").remove();
					item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
					
					if(i !=(length-1)){
	                     i++;
	                     onupload();
	                }else{
	                      imageArray=[];
	                      $(".uploadoper").find("a").eq(1).removeAttr("on");	                        
	                 }
                }
		 	});
		 	
		}
		onupload();
	}
	
	
	
}

//微信上传失败重新上传
function wxreshresh(element,localIds,name){
	element.find(".up_refresh").remove();
	element.find(".up_refreshtxt").remove();
	element.append('<div class="weui-uploader__file-content la-ball-beat la-sm"><i></i><i></i><i></i> </div>');
	wx.uploadImage({
		 	localId: localIds,
		 	isShowProgressTips: 0,
		 	success: function(res) {		 			 
		 			
		 				baseAjax('other/image/upload_image2', 'POST', {
		 					user_id: user_id,
		 					media_id: res.serverId,		 					
		 					work_id: workid
		 				}, function(result) {
							var item=$('#uploaderFiles li[name="'+name+'"]');
							item.addClass("upload_sucess");
							item.find(".la-ball-beat").remove();					
							if(result.data.quality!=0){//照片的一边小于900    照片像素过低可能导致，图片模糊   0=正常；1=比例不符合；2=像素不符合
								item.append('<div class="upload_i_worn"><i class="weui-icon-warn"></i> </div>');
								console.log('quality' +result.data.quality);
							}							
							item.append('<div class="delimportimg"><i class="fa fa-close fa-fw"></i></div>');	
							item.removeClass("weui-uploader__file_status");
							$(".upload_num").text($(".upload_sucess").length);
							$(".uploadoper").find("a").eq(1).show().siblings("a").hide();
							$('#uploaderInput').attr("large_image_num",$('#uploaderInput').attr("image_num")-parseInt($(".upload_num").text()));
							
	                        $(".uploadoper").find("a").eq(1).removeAttr("on");
		 					
		 				})
		 				
		 		},fail: function (res) {
                    var item=$('#uploaderFiles li[name="'+name+'"]')
					item.find(".la-ball-beat").remove();
					item.append('<div class="weui-uploader__file-content up_refresh wx_uprefresh"> <i class="fa fa-refresh fa-lg"></i></div><div class="up_refreshtxt"><span>上传失败</span><span>重新上传</span> </div>');
					$(".uploadoper").find("a").eq(1).removeAttr("on");	                        
	                 
                }
		 	});
	
}
